import axios from 'axios'
import qs from 'qs'
import { getToken } from '.';
import { Toast } from 'antd-mobile';
import { createBrowserHistory } from 'umi'
const history = createBrowserHistory();


axios.defaults.baseURL = process.env.NODE_ENV === 'development'? '/conner': '生产环境源';
axios.defaults.timeout = 8000;

// 添加拦截器
axios.interceptors.request.use(function (config) {

  if (config.method === 'get' || getToken()) {
    config.params = {
      ...config.params,
      token: getToken()
    }
  }

  if (config.method === 'post' || getToken()) {
    config.data = {
      ...config.data,
      token: getToken()
    }
  }
  if (config.method === 'post' &&  config.data) {
    config.data = qs.stringify(config.data)
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

axios.interceptors.response.use(function (res) {
  if (res.data.code === 2000) {
    // 登录状态过期或者未登录
    // 各种清除登录相关缓存
    localStorage.removeItem("token");
    Toast.show({
      icon: 'fail',
      content: '登录状态过期或者未登录',
      afterClose: () => {
        // 去登录页
        history.push('/login')
        history.go(0)
      }
    })
  }
  return res;
}, function (error) {
  return Promise.reject(error);
});

export default axios